#!/bin/bash 

RED='\e[1;31m'
CYAN='\e[1;36m'
NC='\e[0m' # No Color
YLW='\e[1;33m'
WHITE='\e[0;37m'

main_url="http://www.mangafox.com/manga"
wget_param="--tries=10 --retry-connrefused"

## usage
if [ -z $1 ]
then
	echo
	echo -e "${CYAN}[*]${RED} usage: `basename $0` manga_url${NC}"
	echo
	exit
else
	manga_name=`echo $1 | awk -F '/' '{for(i=NF;i>=0;i--){if(length($i)>0){print $i;break;}}}'`
	if [ ! -z "$2" ]
	then
		specific_chapter="$2"
	fi
fi
##

function find_chapters()
{
	TMP="${manga_name}_find_chapters.tmp"
	
	echo -n -e "${CYAN}[*]${RED} Finding total chapters in ${CYAN} $manga_name ${NC}= "
	wget $wget_param -q -nv "${main_url}/${manga_name}/?no_warning=1" -O $TMP
	chapters=`cat $TMP | grep -e 'class="chico">' | grep -v -e '</td>' -e '#listing' | awk -F '"' '{print $2}' | sed 's/^\/manga\///g'`

	count=0
	for c in $chapters
	do
		mkdir -p ./$c
		#echo $c ##debug
		count=$((count+1))
	done
	echo -e "${CYAN}${count}${NC}"
}


function parse_chapter_n_download()
{
	PAGES="pages.tmp"
	PAGE="page_html.tmp"
	
	for chapter in $chapters
	do
		pwd=`pwd`
		
		if [ "$specific_chapter" ]
		then
			mkdir -p "$specific_chapter" 2>/dev/null
			chapter=$specific_chapter
		fi

		cd ./$chapter
		
		## find total number of pages in chapter
		echo -n -e "${CYAN}[*]${RED} Total pages in ${CYAN} $chapter ${NC}= "
		wget -q -nv $wget_param $main_url/$chapter -O $PAGES
		pages=`cat $PAGES | grep '^.*<option value=.*<\/select>.*$' -m1 | awk '{for(i=1;i<=NF;i++){if($(i-1)~"value"){print $i}}}' | sed -e 's/selected//g;s/option//g;s/[<>\/"=]//g;'`
		
		n=0
		for k in $pages
		do
			#echo $k ##debug
			n=$((n+1))
		done
		echo -e "${CYAN}$n${NC}"

		## now i have a list of (1,2,3...).html pages
		for p in $pages
		do
			wget $wget_param  -q -nv $main_url/$chapter/${p}.html -O $PAGE
			img_url=`cat $PAGE | grep 'onclick="return enlarge();' | awk '{for(i=1;i<=NF;i++){if($i~"http://"){print $i}}}' | sed 's/src=//g;s/["=]//g'`
			img=`echo $img_url | awk -F '/' '{print $NF}'`
			echo -e -n "${CYAN}>>${WHITE} $img_url ${RED} ... ${NC}"
			wget $wget_param -q -nv $img_url
			if [ -e $img ]
			then
				echo -e "${CYAN}[done]${NC}"
			else
				echo -e "${YLW}[failed]${NC}"
			fi
		done

		cd $pwd

		if [ "$specific_chapter" ]
		then
			exit;
		fi
done
}


function main()
{
	rm -rf ${manga_name}
	find_chapters
	parse_chapter_n_download
}

main
